import tokenService from '@/auth/tokenManage'
import { getDeviceType } from '@/utils/device'

export const combinedRouterGuard = async (to, from, next) => {
  const deviceType = getDeviceType()

  // 1. 认证检查
  const isLoginPath = to.path === '/login' || to.path.endsWith('/login')
  if (!isLoginPath && !tokenService.isAuthenticated()) {
    return next(`/${deviceType}/login`)
  }
  // 2. 已登录时阻止访问登录页
  if (to.path.endsWith('/login') && tokenService.isAuthenticated()) {
    return next(`/${deviceType}/category`)
  }

  const pathSegments = to.path.split('/')
  const firstSegment = pathSegments[1] || ''

  // 处理不带设备前缀的路径
  if (!['pc', 'mobile'].includes(firstSegment)) {
    const remainingPath = pathSegments.slice(1).join('/')
    const newPath = remainingPath ? `/${deviceType}/${remainingPath}` : `/${deviceType}`
    return next({ path: newPath, query: to.query })
  }

  // 3. 设备路由处理
  // 需要重定向的情况：
  // 1. 访问根路径 '/'
  // 2. 访问的设备类型不匹配当前设备
  if (
    to.path === '/' ||
    (firstSegment === 'pc' && deviceType === 'mobile') ||
    (firstSegment === 'mobile' && deviceType === 'pc')
  ) {
    // 处理根路径
    if (to.path === '/') {
      return next(`/${deviceType}`)
    }

    // 处理设备切换 - 保持相同的路径但切换设备前缀
    const remainingPath = pathSegments.slice(2).join('/')
    const newPath = remainingPath ? `/${deviceType}/${remainingPath}` : `/${deviceType}`
    return next({ path: newPath, query: to.query })
  }

  // 4. 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title
  }

  // 放行
  next()
}
